package com.dq.vo.request;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人 gewenzhen
 * @创建时间 2019/9/10
 * @描述
 */
public abstract class BaseRequest {


    public Map<String, Object> parseMap() throws IllegalArgumentException, IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>(16);
        for (Field param : this.getClass().getFields()) {
            String paramName = param.getName();
            map.put(paramName, param.get(this));
        }
        return map;
    }

    public String toXML() {
        XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyReplacer("-_", "_")));
        xStreamForRequestPostData.alias("xml", this.getClass());
        // 将要提交给API的数据对象转换成XML格式数据Post给API
        return xStreamForRequestPostData.toXML(this);
    }

    public String toJson() {
        return JSON.toJSONString(this);
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        try {
            for (Map.Entry<String, Object> entry : parseMap().entrySet()) {
                sb.append(entry.getKey()).append(":").append(entry.getValue()).append(",");
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
